package cn.cdm.dao;

import cn.cdm.domain.MiaoshaGoods;
import cn.cdm.vo.GoodsVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

public interface GoodsDao {

	/**
	 * 此处需要在yml中配置MyBatis的驼峰命名转换功能，才能将数据库中查询的字段，映射给GoodsVo对象的属性
	 * 开启MyBatis的驼峰命名配置项，mybatis.configuration.mapUnderscoreToCamelCase: true
	 */
//	@Select("select g.id, mg.stock_count from miaosha_goods mg left join goods g on mg.goods_id = g.id")
	@Select("select g.*, mg.* from miaosha_goods mg left join goods g on mg.goods_id = g.id")
	List<GoodsVo> listGoodsVo();

	@Select("select g.*,mg.stock_count, mg.start_date, mg.end_date,mg.miaosha_price " +
			"from miaosha_goods mg left join goods g on mg.goods_id = g.id where g.id = #{goodsId}")
	GoodsVo getGoodsVoByGoodsId(@Param("goodsId") long goodsId);


	/**
	 * ("update miaosha_goods set stock_count = stock_count - 1 where goods_id = #{goodsId}")
	 * 上面update语句，没有设置库存大于0的条件，会将秒杀商品表的库存减为负数，即卖超问题。
	 * 上面的SQL语句，存在此种情况，只剩下1个商品，同时来了req1、req2，两个请求都进行秒杀，最后将库存减为负数(卖超了)
	 * @param g
	 * @return
	 */
	// 下面的SQL语句是原子操作，当库存大于0，才去执行减库存操作，解决卖超问题
	@Update("update miaosha_goods set stock_count = stock_count - 1 where goods_id = #{goodsId} and stock_count > 0")
	int reduceStock(MiaoshaGoods g);

	@Update("update miaosha_goods set stock_count = #{stockCount} where goods_id = #{goodsId}")
	public int reSetStock(MiaoshaGoods miaoshaGoods);
}





















